//
//  PostListViewController.m
//  Buzz API Demo
//
//  Created by Peter Hopkins on 4/22/10.
//  Copyright 2010 Google Inc. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "PostListViewController.h"

#import "Buzz_API_DemoAppDelegate.h"
#import "PostDetailViewController.h"
#import "NewPostViewController.h"

#import "GDataServiceGoogle.h"
#import "GDataOAuthAuthentication.h"
#import "GDataOAuthViewControllerTouch.h"
#import "GTMRegex.h"
#import "GTMNSString+HTML.h"

#import "Author.h"
#import "Post.h"

@implementation PostListViewController

#define kBuzzURL [NSURL URLWithString:@"https://www.googleapis.com/buzz/v1/"]

@synthesize postsTable = postsTable_;
@synthesize postDetailViewController = postDetailViewController_;

- (void)setDao:(BuzzDao *)dao {
  dao_ = [dao retain];
  [postDetailViewController_ setDao:dao];
}


- (void)viewDidLoad {
  UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
                                                                                  target:self
                                                                                  action:@selector(refresh:)] autorelease];
  [[self navigationItem] setLeftBarButtonItem:refreshButton];
}


- (void)viewWillAppear:(BOOL)animated {
  if (consumptionController_ == nil) {
    consumptionController_ = [[dao_ fetchConsumption:self] retain];
  }

  [dao_ syncConsumption];
}


- (void)reset {
  [consumptionController_ release];
  consumptionController_ = nil;

  [postsTable_ reloadData];
}


- (void)refresh:(id)sender {
  [dao_ syncConsumption];
}


#pragma mark Fetched results methods

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
  [postsTable_ beginUpdates];
}


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
  [postsTable_ endUpdates];
}


- (void)controller:(NSFetchedResultsController *)controller
   didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath
     forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {

  switch(type) {
    case NSFetchedResultsChangeInsert:
      [postsTable_ insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
      break;

    case NSFetchedResultsChangeDelete:
      [postsTable_ deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
      break;

    case NSFetchedResultsChangeUpdate:
      [postsTable_ reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
      break;

    case NSFetchedResultsChangeMove:
      [postsTable_ deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
      [postsTable_ insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                         withRowAnimation:UITableViewRowAnimationRight];
      break;

    default:
      break;
  }
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section {
	id <NSFetchedResultsSectionInfo> sectionInfo =
      [[consumptionController_ sections] objectAtIndex:section];
  return [sectionInfo numberOfObjects];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *CellIdentifier = @"Post";

  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                   reuseIdentifier:CellIdentifier] autorelease];
  }
  
	// Configure the cell.
	Post *post = [consumptionController_ objectAtIndexPath:indexPath];

  [[cell textLabel] setText:[post title]];

  NSDateFormatter *timeFormatter;
  timeFormatter = [[[NSDateFormatter alloc] init] autorelease];
  [timeFormatter setDateStyle:NSDateFormatterNoStyle];
  [timeFormatter setTimeStyle:NSDateFormatterShortStyle];

  NSDateFormatter *dateFormatter;
  dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
  [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  [dateFormatter setTimeStyle:NSDateFormatterNoStyle];

  NSDate *date = [post updatedDate];
  [[cell detailTextLabel] setText:[NSString stringWithFormat:@"%@ at %@ on %@",
                                   [[post author] name],
                                   [timeFormatter stringFromDate:date],
                                   [dateFormatter stringFromDate:date]]];

  return cell;
}


- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	Post *post = [consumptionController_ objectAtIndexPath:indexPath];

  [postDetailViewController_ setDao:dao_];
  [postDetailViewController_ showPost:post];

  [[self navigationController] pushViewController:postDetailViewController_ animated:YES];
  [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
  NewPostViewController *controller = [[[NewPostViewController alloc] initWithDao:dao_] autorelease];
  [self presentModalViewController:controller animated:YES];

  return NO;
}

- (void)addTicket:(GDataServiceTicket *)ticket
       addedEntry:(GDataEntryBase *)entry
            error:(NSError *)error {/*
  if (error != nil) {
    [self showApiError:error];
  }

  [self dismissModalViewControllerAnimated:YES];*/
}

- (void)dealloc {
  [imageView_ release];
  [nameLabel_ release];
  [postsTable_ release];

  [postDetailViewController_ release];

  [dao_ release];
  [consumptionController_ release];

  [super dealloc];
}

@end

